cc.FileUtils:getInstance():addSearchPath("src")
cc.FileUtils:getInstance():addSearchPath("res")
-- CC_USE_DEPRECATED_API = true
require "cocos.init"

-- cclog
cclog = function(...)
    print(string.format(...))
end

-- for CCLuaEngine traceback
function __G__TRACKBACK__(msg)
    cclog("----------------------------------------")
    cclog("LUA ERROR: " .. tostring(msg) .. "\n")
    cclog(debug.traceback())
    cclog("----------------------------------------")
end

local function initGLView()
    local director = cc.Director:getInstance()
    local glView = director:getOpenGLView()
    if nil == glView then
        glView = cc.GLViewImpl:create("Lua Empty Test")
        director:setOpenGLView(glView)
    end

    director:setOpenGLView(glView)

    glView:setDesignResolutionSize(480, 320, cc.ResolutionPolicy.NO_BORDER)

    --turn on display FPS
    director:setDisplayStats(true)

    --set FPS. the default value is 1.0/60 if you don't call this
    director:setAnimationInterval(1.0 / 60)
end


local function SaveTableContent(file, obj)
      local szType = type(obj)
      print(szType)
      if szType == "number" then
            file:write(obj)
      elseif szType == "string" then
            file:write(string.format("%s", obj))
      elseif szType == "table" then
            --把table的内容格式化写入文件
            file:write("{ ")
            for i, v in pairs(obj) do
                  -- file:write("[")
                  file:write(string.format("%s", i))
                  -- file:write("]=")
                  file:write("=")
                  SaveTableContent(file, v)
                  file:write(", ")
             end
            file:write("}")
      else
        error("can't serialize a "..szType)
      end
end

local function beginWite()
    file = io.open("./test.lua", "w")
    assert(file)
    file:write("local map_table = {}\n")
    return file
end

local function endWite(file)
    file:write("\nreturn map_table") 
    file:close()
end

local function witeNpcs(file, npcs)
    file:write("\nmap_table.npcs = {\n") 
    for i, v in ipairs(npcs) do
        file:write("    ") 
        -- npcs[i] = {pos = tempPos, id = v.id}
        SaveTableContent(file, "{ id = " .. v.id .. ", pos = " .. "{" .. v.pos.x .. ", " .. v.pos.y .. "}" .. " }")
        file:write(",\n") 
    end
    file:write("}\n") 
end

local function witeDynamicNpcs(file, dynamicNpcs)
    file:write("\nmap_table.dynamicNpcs = {\n") 
    for i, v in ipairs(dynamicNpcs) do
        file:write("    ") 
        SaveTableContent(file, "{ id = " .. v.id .. ", pos = " .. "{" .. v.pos.x .. ", " .. v.pos.y .. "}" .. " }")
        file:write(",\n")
    end
    file:write("}\n") 
end


local mapContentSize = nil
local tileSize = nil
local mapSize = nil
local mapData = {}

local isOutPutSucces = true

local CONVERT_MAP_INDEX = function(index)
    local startPos = { x = 0, y = (mapSize.width) * tileSize.height / 2 }
    local x = (index.x + index.y) * tileSize.width / 2 + startPos.x
    local y = ( (index.y - 1) - (index.x-1) ) * tileSize.height / 2 + startPos.y
    return { x  = x, y = y }
end

local CONVERT_MAP_POS = function(pos)
    local col = pos.x / tileSize.height
    local row = pos.y / tileSize.height
    return CONVERT_MAP_INDEX({ x = col, y = row })
end


local CONVERT_POS_INDEX = function(pos)
    local startPos = { x = 0, y = (mapSize.width) * tileSize.height / 2 }
    local px = (pos.x - startPos.x) * 2 / tileSize.width---- + 2
    local py = (pos.y - startPos.y) * 2 / tileSize.height
    -- print("px and py:", px, py, pos.x, pos.y)
    -- print("CONVERT_POS_INDEX:", (px - py) / 2, (px + py) / 2)
    local col = math.floor((px - py) / 2)
    local row = math.floor((px + py) / 2)
    return { x = col, y = row }
end

-----人不能站在这个点上
function checkIsWrongPos(checkPos)
    if checkIsOutMap(checkPos) == true or mapData[checkPos.y][checkPos.x] == 1 then
        return true
    end
    return false
end
-----这个点是界外
function checkIsOutMap(checkPos)
    if mapData == nil or mapData[checkPos.y] == nil or mapData[checkPos.y][checkPos.x] == nil then
        return true
    end
    return false
end

local function setMap()
    local map = cc.TMXTiledMap:create("test" .. ".tmx")
    map:setAnchorPoint({ x = 0, y = 0 })
    local bg = map:getLayer("bg")
    local tempTexture = bg:getTexture()
    mapContentSize = tempTexture:getContentSize()
    tileSize = map:getTileSize()
    mapSize = map:getMapSize()

    -- print("tempTexture size:", mapContentSize.width, mapContentSize.height)
    -- print("tileSize size:", tileSize.width, tileSize.height)
    -- print("mapSize size:", mapSize.width, mapSize.height)

    mapData = {}
    for j = 0, mapSize.height - 1 do
        mapData[j] = {}
        for i = 0, mapSize.width - 1 do
            mapData[j][i] = 0
        end
    end
    
    ---------------------block----------------------------------------------
    local objGroup = map:getObjectGroup("block")
    local objArr = objGroup:getObjects()
    local objOffset = objGroup:getPositionOffset()
    -- print("objOffset:")
    -- dump(objOffset)

    for i,v in ipairs(objArr) do
        -- print("东城破", v.name, v.x, v.y, tileSize.width, tileSize.height, v.width, v.height)
        local col = math.floor(v.x / tileSize.height)
        local row = math.floor(v.y / tileSize.height)
        -- print("col:", col, "row:", row)

        local w = math.ceil(v.width / tileSize.height)
        local h = math.ceil(v.height / tileSize.height)
        for j = row, row + h - 1 do
            for i = col, col + w - 1 do
                mapData[j][i] = 1
                -- print("中了", j, i)
            end
        end
    end

    -- print("mapData:")
    -- dump(mapData)

    ------------------------------------------------------------------------


    local bornPos = nil
    local mapBgPos = nil

    ----------------------------------------npc--------------------------------------
    local npcGroup = map:getObjectGroup("npc")
    local npcArr = npcGroup:getObjects()
    local npcOffset = npcGroup:getPositionOffset()
    -- print("npcOffset:")
    -- dump(npcOffset)
    local npcInfoArr = {}
    for i,v in ipairs(npcArr) do
        local npcPos = CONVERT_MAP_POS(v)
        npcPos.y = npcPos.y - v.height/2
        -- print("vvvvvv:", v.name, v.x, v.y, npcPos.x, npcPos.y)
        -- local col111 = v.x / tileSize.height
        -- local row111 = v.y / tileSize.height
        -- print("col111:", col111, "row111:", row111)
        local tempRealWidth = v.width*tileSize.width/tileSize.height
        v.width = tempRealWidth
        npcInfo = cc.rect(npcPos.x, npcPos.y, v.width, v.height)
        npcInfo.name = v.name
        
        if v.name == "born" then
            bornPos = npcInfo 
        elseif v.name == "mapBgPos" then
            mapBgPos = {x = npcInfo.x + v.width/2, y = npcInfo.y + v.height/2}
            print("mapBgPos:", mapBgPos.x, mapBgPos.y)
        else
            -- print("npcInfo:", v.name, v.x, v.y)
            npcInfo.mapPosWidth = v.width
            npcInfoArr[#npcInfoArr+1] = npcInfo
            npcInfo.id = checkint(npcInfo.name)
        end
    end

    print("npcInfoArr:")
    dump(npcInfoArr)

    ----------------------------------------------------------------------------------
    

    ----------------------------------------dynamic npc--------------------------------------
    local npcGroup = map:getObjectGroup("dynamicNpc")
    local npcArr = npcGroup:getObjects()
    local dynaimcNpcOffset = npcGroup:getPositionOffset()
    -- print("dynaimcNpcOffset:")
    -- dump(dynaimcNpcOffset)
    local dynamicNpcInfoArr = {}
    for i,v in ipairs(npcArr) do
        local npcPos = CONVERT_MAP_POS(v)
        npcPos.y = npcPos.y - v.height/2
        local tempRealWidth = v.width*tileSize.width/tileSize.height
        npcInfo = cc.rect(npcPos.x, npcPos.y, tempRealWidth, v.height)
        npcInfo.name = v.name
        npcInfo.mapPosWidth = tempRealWidth
        dynamicNpcInfoArr[#dynamicNpcInfoArr+1] = npcInfo
        npcInfo.id = checkint(npcInfo.name)
    end

    -- print("dynamicNpcInfoArr:")
    -- dump(dynamicNpcInfoArr)

    ----------------------------------------------------------------------------------


    ----------------------------------------------------------------------------------


    local file = beginWite()

    SaveTableContent(file, "\n--map_table.mapBgPos = { " .. mapBgPos.x .. "," .. mapBgPos.y .. " }\n")
    SaveTableContent(file, "\nmap_table.bornPos = { " .. checkint(bornPos.x - mapBgPos.x) .. ", " .. checkint(bornPos.y - mapBgPos.y) .. " }\n\n")

    -- witeNpcs(file, { {id = 1000, pos = {x = 1, y = 2} } })
    local npcs = {}
    for i, v in ipairs(npcInfoArr) do
        local tempPos = {x = checkint(v.x + v.width/2 - mapBgPos.x), y = checkint(v.y + v.height/2 - mapBgPos.y)}
        npcs[i] = {id = v.id, pos = tempPos}
        print("v.name", v.name)
        local tempPos = CONVERT_POS_INDEX(cc.p(v.x + v.width/2, v.y + v.height/2))
        local tempPos111 = CONVERT_POS_INDEX(cc.p(v.x, v.y))
        print("v.x, v.y:", v.x, v.y)
        print("tempPos111:", v.name, tempPos111.x, tempPos111.y, v.width, v.height)
        if checkIsWrongPos(tempPos) == true then
            SaveTableContent(file, "--npc position is wrong:" .. v.id .. " = (" .. tempPos.x .. "," .. tempPos.y .. ")" .. "v.x:" .. v.x .. "v.width:" .. v.width .. "  v.y:" .. v.y .. "   v.height:" .. v.height .. "\n")
            isOutPutSucces = false
        end
    end
    witeNpcs(file, npcs)

    local dynamicNpcs = {}
    for i, v in ipairs(dynamicNpcInfoArr) do
        local tempPos = {x = checkint(v.x + v.width/2 - mapBgPos.x), y = checkint(v.y + v.height/2 - mapBgPos.y)}
        dynamicNpcs[i] = {id = v.id, pos = tempPos}
        local tempPos = CONVERT_POS_INDEX(cc.p(v.x + v.width/2, v.y + v.height/2))
        if checkIsWrongPos(tempPos) == true then
            SaveTableContent(file, "--dynamic npc position is wrong:" .. v.id .. "\n")
            isOutPutSucces = false
        end
    end
    witeDynamicNpcs(file, dynamicNpcs)


    endWite(file)
    return map

end


local function main()
    -- avoid memory leak
    collectgarbage("setpause", 100)
    collectgarbage("setstepmul", 5000)

    initGLView()

    -- require "hello2"
    -- cclog("result is " .. myadd(1, 1))

    ---------------

    local visibleSize = cc.Director:getInstance():getVisibleSize()
    local origin = cc.Director:getInstance():getVisibleOrigin()

    -- run
    local sceneGame = cc.Scene:create()
    local tempResultLabel = cc.Label:create()
    tempResultLabel:setString("导出中...")
    tempResultLabel:setSystemFontSize(50)
    tempResultLabel:setPosition(240, 160)
    sceneGame:addChild(tempResultLabel)
    setMap()
    if isOutPutSucces == true then
        tempResultLabel:setString("导出成功！！！")
    else
        tempResultLabel:setString("配置坐标异常")
        tempResultLabel:setTextColor(cc.c4b(255, 0, 0, 255))
    end
    -- run
    cc.Director:getInstance():runWithScene(sceneGame)
end

xpcall(main, __G__TRACKBACK__)
